// ============================== 导出依赖 ============================== //

import UTIL from '../UTIL'
import MOCK from '../MOCK'

let nextId = 15

// ============================== 导出客户端 ============================== //

export class DemoRolePromiseClient {
  // —————————————————————————————— 构造方法 —————————————————————————————— //

  constructor(api) {
    this.api = api
    this.client_ = {}
  }

  // —————————————————————————————— 列表 —————————————————————————————— //

  query(DTO) {
    const { comQuery, roleName, roleType, roleTypesList, beginDate, endDate, status } = DTO.toObject()
    const { page, pageSize, orderBy } = comQuery
    let list = MOCK.ROLE

    if (roleName) list = list.filter((item) => item.roleName.includes(roleName))
    if (roleType) list = list.filter((item) => item.roleType === roleType)
    if (roleTypesList.length) list = list.filter((item) => roleTypesList.includes(item.roleType))
    if (beginDate) list = list.filter((item) => item.createTime >= beginDate)
    if (endDate) list = list.filter((item) => item.createTime < endDate)
    if (status) list = list.filter((item) => item.status === status)

    if (orderBy) {
      const [key, type] = orderBy
      list = [...list].sort((a, b) => (type === 'asc' ? a[key] - b[key] : b[key] - a[key]))
    }

    const contentList = list.slice(pageSize * (page - 1), pageSize * page)
    const resp = UTIL.listResp(list.length, JSON.parse(JSON.stringify(contentList)))
    return UTIL.promiseReturn(resp)
  }

  // —————————————————————————————— 增 —————————————————————————————— //

  create(DTO) {
    const { roleName, roleType, roleTypesList, remark } = DTO.toObject()
    const id = `${nextId}${nextId}${nextId}`
    nextId++
    MOCK.ROLE.push({ id, tenantNo: 1, roleName, roleType, roleTypesList, remark, createTime: Date.now() })
    const resp = UTIL.submitResp()
    return UTIL.promiseReturn(resp)
  }

  // —————————————————————————————— 改 —————————————————————————————— //

  update(DTO) {
    const { id, roleName, roleType, roleTypesList, remark } = DTO.toObject()
    const matched = MOCK.ROLE.find((item) => item.id === id)
    if (matched) Object.assign(matched, { roleName, roleType, roleTypesList, remark })
    const resp = UTIL.submitResp()
    return UTIL.promiseReturn(resp)
  }

  // —————————————————————————————— 删 —————————————————————————————— //

  delete(DTO) {
    const { id } = DTO.toObject()
    const index = MOCK.ROLE.findIndex((item) => item.id === id)
    if (index >= 0) MOCK.ROLE.splice(index, 1)
    const resp = UTIL.submitResp()
    return UTIL.promiseReturn(resp)
  }
}
